package com.chenwc.httputil;

import com.chenwc.enums.HttpsAlgorithmEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

/**
 * HttpURLConnection绕过HTTPS的SSL验证
 * @author chenwc
 */
public class TrustAllHosts {

    private static final Logger log = LoggerFactory.getLogger(TrustAllHosts.class);

    /**
     * 覆盖java默认的证书验证
     */
    private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }
    }};

    /**
     * 设置不验证主机
     */
    public static final HostnameVerifier DO_NOT_VERIFY = (hostname, session) -> true;

    /**
     * 信任所有
     *
     * @param connection https连接
     * @return SSLSocketFactory
     */
    public static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
        SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
        try {
            //设置HTTPS的加密算法名称
            SSLContext sc = SSLContext.getInstance(HttpsAlgorithmEnum.TLSV_1_2.getAlgorithm());
            sc.init(null, trustAllCerts, new SecureRandom());
            SSLSocketFactory newFactory = sc.getSocketFactory();
            log.info("SSLContext Version: {}", sc.getProtocol());
            connection.setSSLSocketFactory(newFactory);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return oldFactory;
    }
}
